package com.test.fundible.fundible_03_login;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.test.fundible.fundible_00_analytics.fundibleevent.FundibleIAnalyticsEvent;
import com.test.fundible.fundible_00_analytics.FundibleUtil.FundibleAnalyticsUtil;
import com.test.fundible.R;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.Othe_fundiblersInfo;
import com.test.fundible.fundible_00_customer_service.Customer_fundibleServiceDialog;
import com.test.fundible.fundible_00_utils.Kind_fundibleTip_fundibleDialog;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleConfigs;
import com.test.fundible.fundible_00_utils.FundibleUtil;

import org.json.JSONException;
import org.json.JSONObject;


public class LoginAc_fundibletivity extends AppCompatActivity {

    private View mobileBgView;
    private TextView areaCodeTv;
    private TextView mobileTitleTv,vercodeTitleTv;
    private EditText mobileEt,vercodeEt;
    private Button sendCodeBtn,getStartBtn;
    private ImageButton ppIb;
    private TextView ppTv;

    private boolean agreement_fundibleFlag = true;

    private final View.OnClickListener sendCo_fundibledeCl = v -> {

        String mobi_fundiblele = mobileEt.getText().toString().trim();

        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","SEND_CODE_CLICK",mobi_fundiblele);

        if (TextUtils.isEmpty(mobi_fundiblele)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_fundible),Toast.LENGTH_SHORT).show();
            return;
        }

        startLoading(this,"");
        OkHttpUtil.getInstance_fundible().requestCode(mobi_fundiblele,this::onSendCodeResponse_fundible);
    };

    private final View.OnClickListener log_fundibleinCl = v -> {

        String mob_fundibleile = mobileEt.getText().toString().trim();
        String vercode = vercodeEt.getText().toString().trim();

        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","CONFIRM_CLICK",mob_fundibleile);

        if (!agreement_fundibleFlag){
            new Kind_fundibleTip_fundibleDialog(
                this,
                getString(R.string.kind_tips_login_desc),
                getString(R.string.kind_tips_login_btn),
                    () -> setAgreement_fundibleFlag(true)
            ).show();
            return;
        }

        if (TextUtils.isEmpty(mob_fundibleile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_fundible),Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(vercode)){
            Toast.makeText(this,getString(R.string.tips_enter_vercode_fundible),Toast.LENGTH_SHORT).show();
            return;
        }

        //测试账号自动登录
        if (App_fundibleShow_fundibleCustomize.getInstance_fundible().isTestAccount_fundible(mob_fundibleile)){
            startLoading(this,"");
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", App_fundibleShow_fundibleCustomize.getInstance_fundible().getTestToken_fundible(mob_fundibleile));
                jsonObject.put("userId", mob_fundibleile);
                jsonObject.put("type", FundibleConfigs.LOGIN_TYPE_OL_fundibleD);
                jsonObject.put("isAdSource","NO");
                Log_fundibleinInfo.par_fundiblese(jsonObject);
                onLoginSucc_fundibleessResponse();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }
        OkHttpUtil.getInstance_fundible().usLgWithCode(mob_fundibleile,vercode,this::onLoginSucc_fundibleessResponse,null);

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fundible_login);
        //tag2024
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        mobileBgView = findViewById(R.id.afl_view_mobile_bg);
        areaCodeTv = findViewById(R.id.afl_tv_areacode);
        mobileTitleTv = findViewById(R.id.afl_tv_mobile_title);
        vercodeTitleTv = findViewById(R.id.afl_tv_vercode_title);
        mobileEt = findViewById(R.id.afl_et_mobile);
        vercodeEt = findViewById(R.id.afl_et_vercode);
        sendCodeBtn = findViewById(R.id.afl_btn_sendcode);
        getStartBtn = findViewById(R.id.afl_btn_getstart);
        ppIb = findViewById(R.id.afl_ib_pp);
        ppTv = findViewById(R.id.afl_tv_pp);

        ini_fundiblet();
    }

    @Override
    protected void onResume() {
        super.onResume();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","START","");
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","END","");
    }

    private void ini_fundiblet(){

        findViewById(R.id.afl_ib_customerservice).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","CUSTOMER_SERVICE_CLICK","");
            new Customer_fundibleServiceDialog(this).show();
        });

        //初始化登录流程
        String areaCode = FundibleUtil.getAreaCode_fundible();
        areaCodeTv.setText(areaCode);
        FundibleUtil.setAreaCode_fundible(areaCode);

        sendCodeBtn.setOnClickListener(sendCo_fundibledeCl);
        getStartBtn.setOnClickListener(log_fundibleinCl);

        //初始化协议
        ppIb.setOnClickListener(v -> setAgreement_fundibleFlag(!agreement_fundibleFlag));
        ppTv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","STATEMENT_CLICK","");
            String agreementUrl = App_fundibleShow_fundibleCustomize.getInstance_fundible().getAgreementUrl_fundible();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //手机号输入监听
        mobileEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileEt.getText().toString().trim();
                String vercode = vercodeEt.getText().toString().trim();

                //登录按键背景色变化
                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode))getStartBtn.setBackgroundResource(R.drawable.bg_gray_rc16dp);
                else getStartBtn.setBackgroundResource(R.drawable.bg_green_rc16dp);
            }
        });

        //验证码输入监听
        vercodeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileEt.getText().toString().trim();
                String vercode = vercodeEt.getText().toString().trim();

                //登录按键背景色变化
                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode))getStartBtn.setBackgroundResource(R.drawable.bg_gray_rc16dp);
                else getStartBtn.setBackgroundResource(R.drawable.bg_green_rc16dp);

                if (s.length() == 4){

                    OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN","OTP_DONE",vercode);

                    if (TextUtils.isEmpty(mobile)) return;

                    //测试账号自动登录
                    if (App_fundibleShow_fundibleCustomize.getInstance_fundible().isTestAccount_fundible(mobile)){
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("token", App_fundibleShow_fundibleCustomize.getInstance_fundible().getTestToken_fundible(mobile));
                            jsonObject.put("userId", mobile);
                            jsonObject.put("type", FundibleConfigs.LOGIN_TYPE_OL_fundibleD);
                            jsonObject.put("isAdSource","NO");
                            Log_fundibleinInfo.par_fundiblese(jsonObject);
                            onLoginSucc_fundibleessResponse();
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        return;
                    }

                    startLoading(LoginAc_fundibletivity.this,"");
                    OkHttpUtil.getInstance_fundible().usLgWithCode(mobile,vercode,() -> onLoginSucc_fundibleessResponse(),null);

                }

            }
        });

        //手机号输入框焦点监听
        mobileEt.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus){
                mobileBgView.setBackgroundResource(R.drawable.bg_white_rc18dp_border_green_1dp);
                mobileTitleTv.setTextColor(getColor(R.color.green_light));
            }else {
                mobileBgView.setBackgroundResource(R.drawable.bg_white_rc18dp_border_gray_1dp);
                mobileTitleTv.setTextColor(getColor(R.color.gray));
            }
        });

        //验证码输入框焦点监听
        vercodeEt.setOnFocusChangeListener(((v, hasFocus) -> {
            if (hasFocus){
                vercodeEt.setBackgroundResource(R.drawable.bg_white_rc18dp_border_green_1dp);
                vercodeTitleTv.setTextColor(getColor(R.color.green_light));
            }else {
                vercodeEt.setBackgroundResource(R.drawable.bg_white_rc18dp_border_gray_1dp);
                vercodeTitleTv.setTextColor(getColor(R.color.gray));
            }
        }));

    }

    private void setAgreement_fundibleFlag(boolean agreement_fundibleFlag) {
        this.agreement_fundibleFlag = agreement_fundibleFlag;
        ppIb.setBackgroundResource(agreement_fundibleFlag ? R.drawable.icon_check_true :R.drawable.icon_check_false);
    }

    @SuppressLint("SetTextI18n")
    public void onSendCodeResponse_fundible(){

        //老用户直接登录
        String mobile = mobileEt.getText().toString().trim();
        JSONObject jsonObject = Othe_fundiblersInfo.getInstance_fundible().getSendOtpCodeJson_fundible();
        if (jsonObject!=null){
            String directLogin = jsonObject.optString("directLoginFlag");
            if (directLogin.equalsIgnoreCase("YES")) {
                OkHttpUtil.getInstance_fundible().userLg_OldUser(mobile,this::onLoginSucc_fundibleessResponse);
                return;
            }
        }

        stopLoading();

        Toast.makeText(this,getString(R.string.tips_vercode_send_success_fundible),Toast.LENGTH_SHORT).show();
        sendCodeBtn.setOnClickListener(null);
        sendCodeBtn.setBackgroundResource(R.drawable.bg_gray_rc18dp);


        new Thread(() -> {

            int count = 60;

            while (count-- > 0){
                final int finalCount = count;
                runOnUiThread(() -> sendCodeBtn.setText(finalCount+"s"));
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(() -> {
                sendCodeBtn.setOnClickListener(sendCo_fundibledeCl);
                sendCodeBtn.setText(getString(R.string.resend));
                sendCodeBtn.setBackgroundResource(R.drawable.bg_green_rc18dp);
            });

        }).start();

    }

    public void onLoginSucc_fundibleessResponse(){

        FundibleUtil.setMobile_fundible(mobileEt.getText().toString().trim());
        FundibleUtil.setToken_fundible(Log_fundibleinInfo.getIns_fundibletance().getT_fundibleoken());
        FundibleUtil.setUserId_fundible(Log_fundibleinInfo.getIns_fundibletance().getUse_fundiblerId());
        FundibleUtil.setIsAdSource_fundible(Log_fundibleinInfo.getIns_fundibletance().getIs_fundibleAdSource());

        if (Log_fundibleinInfo.getIns_fundibletance().getT_fundibleype().equalsIgnoreCase(FundibleConfigs.LOGIN_T_fundibleYPE_REGISTER))
            FundibleAnalyticsUtil.INSTANCE.addEvent_fundible(FundibleIAnalyticsEvent.AT_REGISTER);

        FundibleAnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo_fundible();

        OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onUserProc_fundibleessResponse);

    }

    public void onUserProc_fundibleessResponse(){
        stopLoading();
        startActivity(new Intent(this, MainAct_fundibleivity.class));
        finish();
    }

}